package com.nuo.backend.common.excel.service;


import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.nuo.backend.common.exception.GlobalException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public interface BaseIService<T> extends IService<T> {


    void saveOrUpdateBatch(List<T> list, Class<T> clazz);

    default void saveOrUpdateBatch(List<T> list, String field, String prop, Class<T> clazz) {
        try {
            Field p = clazz.getDeclaredField(prop);
            Field id = clazz.getDeclaredField("id");
            p.setAccessible(true);
            id.setAccessible(true);
            Map<String, T> map = new HashMap<>(100);
            for (T t : list) {
                map.put(p.get(t).toString(), t);
            }
            List<T> tList = list(new QueryWrapper<T>().in(field, map.keySet()));
            for (T t : tList) {
                id.set(map.get(p.get(t).toString()), id.get(t));
            }
            saveOrUpdateBatch(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    default boolean validData(T t, AnalysisContext context) {
        int row = context.readRowHolder().getRowIndex() + 1;

        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getAnnotation(ExcelProperty.class) != null) {
                try {
                    if (field.get(t) == null) {
                        throw new GlobalException("导入失败, 第 " + row + " 行 " + field.getAnnotation(ExcelProperty.class).value()[0] + "为空");
                    }
                } catch (Exception e) {
                    throw new GlobalException(e.getMessage());
                }
            }

        }
        return true;
    }
}
